package leetcode


fun main(args: Array<String>) {
    println(Solution().myAtoi("41"))
}


class Solution {
    fun myAtoi(str: String): Int {
        if (str.isEmpty()) return 0
        val sb = StringBuffer(str.length)
        var index = 0
        var negative = false

        var c = ' '
        while ((c == ' ') && index < str.length) {
            c = str[index++]
        }


        if (index >= str.length) {
            return if (c in '0'..'9')
                c.toInt() - 48
            else 0
        }

        if (c !in '0'..'9' && c != '-' && c != '+')
            return 0


        if (c == '-' || c == '+') {
            //符号开头，此时后面必须跟的是数字
            if (str[index] !in '0'..'9')
                return 0
            negative = c == '-'

            c = str[index]
        } else {
            index--
        }

        //是否已经去除开头的0
        var discard = false
        while (c in '0'..'9' && index < str.length) {
            if (c == '0' && !discard)
            else {
                discard = true
                sb.append(c)
            }


            index++
            if (index >= str.length)
                break
            c = str[index]
        }

        val s = sb.toString()
        if (s.isEmpty())
            return 0
        if (negative) {
            if (s.length > "2147483648".length)
                return Int.MIN_VALUE
            if (s.length == "2147483648".length)
                if (s >= "2147483648")
                    return Int.MIN_VALUE
            return -s.toInt()

        } else {
            if (s.length > "2147483647".length)
                return Int.MAX_VALUE
            if (s.length == "2147483647".length)
                if (s > "2147483647")
                    return Int.MAX_VALUE
            return s.toInt()
        }

    }
}